<template>
  <!-- 上传组件 -->
  <el-upload v-model="imgUrl" class="single-uploader relative" :show-file-list="false" list-type="picture-card"
    :before-upload="handleBeforeUpload" :http-request="uploadFile" auto-upload v-loading="loading">
    <img v-if="img_url" :src="urlReq(img_url)" class="w-100% h-auto" />
    <el-icon v-else class="single-uploader__icon"><i-ep-plus /></el-icon>
    <div class="absolute w-full h-full left-0 top-0 bg-[rgba(0,0,0,0.4)] flex items-center justify-center"
      v-if="img_url">
      <div class="p-15px">
        <el-icon class="text-30px text-white!" @click.stop="download">
          <Download />
        </el-icon>
      </div>
      <div class="p-15px">
        <el-icon class="text-30px text-white!" @click.stop="removeImg">
          <Delete />
        </el-icon>
      </div>
    </div>
  </el-upload>
</template>

<script setup>
import Api from "@/api/common";
import { ref, watch } from 'vue';
import { useVModel } from '@vueuse/core';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  // 添加 attrs 属性
  uploadParams: {
    type: Object,
    default: () => ({})
  },
  // 添加返回值类型配置
  returnType: {
    type: String,
    default: "url", // 默认返回url，可选值: "url" 或 "path"
    validator: (value) => ["url", "path"].includes(value)
  }
});

const emit = defineEmits(["update:modelValue"]);
const imgUrl = useVModel(props, "modelValue", emit);
const img_url = ref('');
const loading = ref(false)

// 监听两个数据源来更新img_url
watch([() => props.modelValue, () => props.formData.image_url], ([modelValue, imageUrl]) => {
  // 优先使用modelValue，如果没有则使用formData.image_url
  img_url.value = modelValue || imageUrl || '';
}, {
  immediate: true,
});

// 处理上传参数
const handleUploadParams = (formData) => {
  if (props.uploadParams && Object.keys(props.uploadParams).length > 0) {
    Object.entries(props.uploadParams).forEach(([key, value]) => {
      if (typeof value === 'string' && !!props.formData[value]) {
        formData.append(key, props.formData[value]);
      } else if (!props.formData[value]) {
        ElMessage.error(t(`hint.${value}`));
      }
    });
  }
};

/**
 * 自定义图片上传
 *
 * @param options
 */
const uploadFile = async (options) => {
  loading.value = true
  console.log('options.file===>',options.file)
  const formData = new FormData();
  // 确保文件正确添加到 FormData
  formData.append('file', options.file);
  // handleUploadParams(formData)
  try {
    const {url, path} = await Api.upload(formData);
    img_url.value = url; // 始终使用url来显示图片
    // 根据returnType决定返回url还是path
    imgUrl.value = props.returnType === "path" ? path : url;
  } catch (error) {
    ElMessage.error('上传失败');
  } finally {
    loading.value = false
  }
}

// 修改urlReq方法，确保无论存储的是path还是url，都能正确显示图片
const urlReq = (url) => {
  if (/^https?:\/\//.test(url)) {
    console.log('属性值是一个链接');
    console.log('url====>',url)
    return url
  } else {
    console.log('属性值不是一个链接');
    return `${import.meta.env.VITE_IMG_URL}${url}`
  }
}

/**
 * 限制用户上传文件的格式和大小
 */
const handleBeforeUpload = (file) => {
  if (file.size > 2 * 1048 * 1048) {
    ElMessage.warning("上传图片不能大于2M");
    return false;
  }
   // 检查 formData 中的值是否存在
  //  const missingFields = [];
  // if (props.uploadParams && Object.keys(props.uploadParams).length > 0) {
  //   Object.entries(props.uploadParams).forEach(([key, value]) => {
  //     if (typeof value === 'string' && !props.formData[value]) {
  //       missingFields.push(value);
  //     }
  //   });
  // }

  // if (missingFields.length > 0) {
  //   for(let i = 0; i < missingFields.length; i++) {
  //     ElMessage.error(t(`hint.${missingFields[i]}`));
  //   }
  //   return false;
  // }
  return true;
}
const removeImg = () => {
  imgUrl.value = ""
  img_url.value = ""
}
const download = () => {
  //图片的地址 
  fetch(imgUrl.value).then(res => res.blob()).then(blob => {
    // 创建a标签
    var link = document.createElement('a');
    // 设置a标签为不可见
    link.style.display = 'none';
    // 将a标签添加到body
    document.body.appendChild(link);
    // 生成Blob URL并设置给a标签的href属性
    var url = window.URL.createObjectURL(blob);
    link.href = url;
    // 设置a标签的download
    link.download = 'game';
    // 模拟点击事件进行下载
    link.click();
    //下载完成后清理URL对象和a标签
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
  })
}
</script>

<style scoped lang="scss">
.single-uploader {
  overflow: hidden;
  cursor: pointer;
  border: 1px var(--el-border-color) solid;
  border-radius: 6px;

  &:hover {
    border-color: var(--el-color-primary);
  }

  &__image {
    display: block;
    width: 178px;
    height: 178px;
  }

  &___icon {
    width: 178px;
    height: 178px;
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
}
</style>
